package com.ss.web.tagmark.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.ss.web.tagmark.dao.TagDao;
import com.ss.web.tagmark.dao.UserTagDao;
import com.ss.web.tagmark.entity.TagInfo;

@Service
public class TagService extends BaseService<TagInfo> {
	@Autowired
	private TagDao tagDao;
	@Autowired
	private UserTagDao userTagDao;

	/**
	 * 根据页面输入的内容查询出匹配的值
	 *
	 * @param q
	 * @return
	 */
	public List<TagInfo> find4Search(String q) {
		return tagDao.find4Search(q);
	}

	/**
	 * 批量添加标签信息
	 *
	 * @param tagNames
	 *            标签内容
	 * @return
	 */
	@Transactional
	public List<TagInfo> batchAdd(String[] tagNames) {
		List<TagInfo> ret = new ArrayList<>();
		if (tagNames == null || tagNames.length < 1) {
			return ret;
		}
		for (String tagName : tagNames) {
			if (StringUtils.isBlank(tagName)) {
				continue;
			}
			tagName = tagName.replaceAll("\\s|　", "");//把空格去除
			TagInfo tag = tagDao.findByName(tagName);
			if (tag == null) {
				tag = new TagInfo();
				tag.setName(tagName);
				try {
					tag.setNamePy(PinyinHelper.convertToPinyinString(tagName, "", PinyinFormat.WITHOUT_TONE));
					tag.setNamePyShort(PinyinHelper.getShortPinyin(tagName));
				} catch (Exception e) {
				}
				tagDao.save(tag);
			}
			ret.add(tag);
		}
		return ret;
	}

	@Transactional
	public void deleteById(Long tagId) {
		if (tagId == null) {
			return;
		}
		// 删除对应的tag
		tagDao.deleteById(tagId);
		// 删除用户与tag的对应关系
		userTagDao.deleteByTagId(tagId);
	}

	/**
	 * 获取指定用户的所有标签信息
	 *
	 * @param userId
	 * @return
	 */
	public List<TagInfo> getTagsByUser(Long userId) {
		if (userId == null) {
			return null;
		}
		return tagDao.findByUserId(userId);
	}

}
